﻿/// <reference path="Core.js" />
/// <reference path="jquery-1.9.1.js" />
var id;
$(function ()
{
    id = "ListInnerContainer";
    core.View.Load(EntityName, id);
    //zw
    //添加中文日期格式模块
    $.fn.datetimepicker.dates['zh-CN'] = {
        days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
        daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
        daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
        months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
        today: "当前时间",
        suffix: [],
        meridiem: ["上午", "下午"]
    };
    $('.form-time').datetimepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd hh:ii',
        weekStart: 1,
        autoclose: true
    });
    if (DoNotShowButton <= 0)
    {
        if (Privilege.CREATE > 0) $('#btn_add').css('display', 'inline-block');
        if (ViewName.toLowerCase().indexOf('deletedview') < 0 && Privilege.DELETE > 0) $('#btn_delete').css('display', 'inline-block');
        if (Privilege.ASSIGN > 0) $('#btn_assign').css('display', 'inline-block');
        if (ViewName.toLowerCase().indexOf('deletedview') >= 0 && Privilege.DELETE > 0)
        {
            $('#btn_recoverSoftDelete').css('display', 'inline-block');
        }
    }
    //滚动
    $("#ListContainer thead").css({ "background": "#F5F6FA" });
    $("div.table-responsive").scroll(function ()
    {
        var left = (-1) * $(this).scrollLeft();
        console.log(left);
        var top = $(this).scrollTop();
        //$("#ListContainer thead").css("left", left);
        $("#ListContainer-title").css("top", top);

    });
    $("#ListContainer").scrollTop(30);

});


/// <reference path="Core.js" />
/// <reference path="jquery-1.9.1.js" />

if (typeof (core) == 'undefined')
    core = {};

core.View = {};
core.EntityName = {};
core.ViewName = {};
core.View.Url = {};

core.ViewField = {};
core.EntityOption = {};
core.EntityViews = {};
core.View.Orderby = {};
core.ListData = {};
core.View.Option = {};
core.View.OptionBackup = {};
core.View.isHaveFilter = {};
core.View.PageParam = {};



core.View.Load = function (entityname, id, ishaveSearch, ishaveView, option, InitShowView, DefaultViewName, isHaveFilter)
{

    if ($.getQueryString("type") == "N2N")
    {
        var LinkEntity = {};
        LinkEntity.aid = $.getQueryString("linkentityid") == null ? "" : $.getQueryString("linkentityid");
        LinkEntity.entityM = $.getQueryString("entityMname") == null ? "" : $.getQueryString("entityMname");
        LinkEntity.entityA = $.getQueryString("entityAname") == null ? "" : $.getQueryString("entityAname");
        LinkEntity.entityB = $.getQueryString("entityBname") == null ? "" : $.getQueryString("entityBname");

        core.View.LinkEntity = LinkEntity;
        $("#div_nomal").css("display", "none");
        $("#div_N2N").css("display", "block");
    }

    //是否生成操作列
    if (typeof (option) != 'undefined')
        core.View.Option[id] = option;
    if (option == null)
        core.View.Option[id] = [];

    core.View.OptionBackup[id] = core.View.Option[id];

    //自动生成页面框架
    if (typeof (ishaveSearch) == 'undefined')
        ishaveSearch = true;
    if (typeof (ishaveView) == 'undefined')
        ishaveView = true;
    if (typeof (isHaveFilter) == 'undefined')
        isHaveFilter = true;
    if (typeof (InitShowView) == 'undefined')
        InitShowView = true;
    core.View.isHaveFilter[id] = isHaveFilter;
    if (typeof (DefaultViewName) == 'undefined' || DefaultViewName == null)
        DefaultViewName = ViewName;
    if (ishaveSearch)
    {
        $("#" + id).children().append(' <!--搜索框-->\
                                        <div class="col-md-6" style="width: 50%;z-index:1;display:inline-block">\
                                            <div class="input-group">\
                                                <input type="text" class="form-control" name="txt_searchValue" onkeypress=\'if (event.keyCode == 13) core.View.Search("' + id + '")\' placeholder="搜索..." />\
                                                <span class="input-group-btn">\
                                                    <button class="btn btn-primary ng-binding" name="btn_search" onclick=\'core.View.Search("' + id + '")\' type="button">\
                                                        搜索</button>\
                                                </span>\
                                            </div></div>');
    }
    if (ishaveView)
    {
        $("#" + id).children().append(' <!--视图切换-->\
                                            <div class="col-md-3 pull-right" style="width:25%;margin-bottom:8px;visibility: hidden;">\
                                                <select name="ViewList" onchange="core.View.SwitchView(this,\''+ id + '\');" class="form-control col-md-3 pull-right"></select>\
                                            </div>');
    }
    $("#" + id).children().append('<!--列表-->\
                                            <div class="col-md-12" >\
                                                <div  id="ListContainer" class="col-md-12 table-responsive" style="overflow-x:auto !important; width:100%; overflow:auto;">\
                                                <div  id="ListContainer-title" class="col-md-12 table-responsive" style="overflow:visible !important; width:100%;">\
                                                <table class="table table-hover" style="table-layout:fixed" name="ListContainer">\
                                                    <colgroup>\
                                                    </colgroup>\
                                                    <thead>\
                                                    </thead>\
                                                </table>\
                                                </div>\
                                                <div  id="ListContainer-body" class="col-md-12 table-responsive" style="overflow:visible !important; width:100%;">\
                                                <table class="table table-hover" style="table-layout:fixed" name="ListContainer">\
                                                    <colgroup>\
                                                    </colgroup>\
                                                    <tbody>\
                                                    </tbody>\
                                                </table>\
                                                </div>\
                                                </div>\
                                                <nav name="ListPageing" style="float: right;">\
                                                    <ul class="pagination" style="margin: 0;">\
                                                        <li><a href="javascript:void(0);" name="pageFirst" aria-label="Firset" onclick=\'core.View.FirstPage("'+ id + '");\'><span aria-hidden="true">&laquo;</span>\
                                                        </a></li>\
                                                        <li><a href="javascript:void(0);" name="pagePrevious" aria-label="Previous" onclick=\'core.View.PrePage("' + id + '");\'><span aria-hidden="true">&lsaquo;</span>\
                                                        </a></li>\
                                                        <li><span name="pageInfo">0\0(共0条)</span></li>\
                                                        <li><a href="javascript:void(0);" name="pageNext" aria-label="Next" onclick=\'core.View.NextPage("' + id + '");\'><span aria-hidden="true">&rsaquo;</span>\
                                                        </a></li>\
                                                        <li><a href="javascript:void(0);" name="pageLast" aria-label="Last" onclick=\'core.View.LastPage("' + id + '");\'><span aria-hidden="true">&raquo;</span>\
                                                        </a></li>\
                                                    </ul>\
                                                </nav>\
                                            </div>');

    //滚动表格高度控制
    var height = window.innerHeight - 153;
    $("#ListContainer").height(height);

    core.EntityName[id] = entityname;

    core.View.GetEntityData(DefaultViewName, id);
    core.ViewName[id] = DefaultViewName;

    core.View.FilterData[id] = {};
    core.View.FilterData[id]["Conditions"] = [];
    if ($.getQueryString("attribute") != null &&
        $.getQueryString("attribute") != "" &&
        $.getQueryString("linkentityid") != null &&
        $.getQueryString("linkentityid") != "")
    {
        core.View.FilterData[id]["Conditions"].push(JSON.parse('{"AttributeName":"' + $.getQueryString("attribute") + '","Operator":"equal","Values":[{ "Id":"' + $.getQueryString("linkentityid") + '" }]}'));
    }
    core.View.FilterData[id]["FilterOperator"] = "AND";
    core.View.FilterData[id]["Filters"] = [];

    core.View.SearchFilter[id] = {};
    core.View.SearchFilter[id]["Conditions"] = [];
    core.View.SearchFilter[id]["FilterOperator"] = "OR";

    core.View.BindHeader(core.EntityName[id], id, InitShowView);
    var flag = 0;
    var firstIndex = -1;
    $(document).keydown(function (event)
    {
        if (event.keyCode == 16)
        {
            $(document).bind("selectstart", function () { return false; });
            flag = 1;
        }

    });
    $(document).keyup(function (event)
    {
        flag = 0;
    });

    //列表checked优化
    //$(document).on('click', '#' + id + ' [name=ListContainer] tbody tr', function (e) {
    //    e = e || window.event;
    //    var target = e.target || e.srcElement;
    //    var checkBox = $(this).find('td:first').find('input:first');
    //    var checkBoxStatus = $(this).find('td:first').find('input:first').prop('checked');
    //    $("table[name=ListContainer] td input[type=checkbox][oid]").prop('checked', false);

    //    checkBox.prop('checked', true);
    //    //if (checkBoxStatus == true) {
    //    //    checkBox.prop('checked', false);
    //    //}
    //    //else {
    //    //    checkBox.prop('checked', true);
    //    //}

    //});
    $(document).on('click', '#' + id + ' [name=ListContainer] tbody tr', function (e)
    {
        e = e || window.event;
        var target = e.target || e.srcElement;
        var Ocheckall = $(this).parent('tbody').parent('table').parent("div[id=ListContainer-body]").siblings("div[id=ListContainer-title]").eq(0).find('table').find('thead').find('tr').find('th:first').find('input');
        if (Ocheckall.prop('checked'))
        {
            Ocheckall.prop('checked', false);
        }
        var checkBox = $(this).find('td:first').find('input:first');
        var start = firstIndex;
        var end = $(this).index();
        var noChecked = true;
        var checkBoxStatus = $(this).find('td:first').find('input:first').prop('checked');

        if (flag == 0)
        {
            firstIndex = $(this).index();
            $("table[name=ListContainer] td input[type=checkbox][oid]").prop('checked', false);
            $('#' + id + ' [name=ListContainer] tbody tr').each(function ()
            {
                var index = $(this).index();
                if (index == end)
                {
                    $(this).css('background-color', '#CCE8FF');
                } else
                {
                    $(this).css('background-color', '#fff');
                }
            });
        }
        if (flag == 1)
        {
            $('#' + id + ' [name=ListContainer] tbody tr').each(function ()
            {
                if ($(this).find('td:first').find('input:first').prop("checked") == true)
                {
                    noChecked = false;
                }
            });
            if (noChecked)
            {
                firstIndex = $(this).index();
            } else
            {
                if (start > end)
                {
                    start = [end, end = start][0];
                }
                if (firstIndex >= 0)
                {
                    $('#' + id + ' [name=ListContainer] tbody tr').each(function ()
                    {
                        var index = $(this).index();
                        if (index >= start && index <= end)
                        {
                            $(this).find('td:first').find('input:first').prop("checked", true);
                            $(this).css('background-color', '#CCE8FF');
                        } else
                        {
                            $(this).find('td:first').find('input:first').prop("checked", false);
                            $(this).css('background-color', '#fff');
                        }
                    });
                }
            }
        }
        checkBox.prop('checked', true);

    });
    $(document).on('click', '#' + id + ' [name=ListContainer] tbody tr td input', function (e)
    {
        e = e || window.event;
        var target = e.target || e.srcElement;
        var tr = $(this).parent().parent();
        if ($(this).prop("checked"))
        {
            tr.css("background-color", "#CCE8FF");
        } else
        {
            tr.css("background-color", "#fff");
        }

    });

    //tr双击事件
    core.View.dblclick = function (e)
    {

        var temp = e;

        core.OpenEntity(temp, 'ListInnerContainer');
    }

    $(document).on('click', '#' + id + ' [name=ListContainer] a,button,input', function (e)
    {
        //立即停止捕获/冒泡
        e.stopPropagation();
    });

}

core.View.BindHeader = function (entityname, id, InitShowView)
{
    $("#" + id + " [name=pageHeader]").text("List " + entityname);

    $("#" + id + " [name=ViewList]").html(core.Util.CreateOptions(core.EntityViews[id], core.ViewName[id]));
    $("#" + id + " [name=ViewList] option[value='']").remove();
    core.View.GenerateList(id, InitShowView);
}
core.View.GenerateList = function (id, InitShowView, pagenum, pagesize)
{
    $("#" + id + " [name=ListContainer] colgroup").html(core.View.BindListColgroup(id));

    $("#" + id + " [name=ListContainer] thead").html(core.View.BindListHeader(id));

    if ($("#" + id + " [name=ListContainer] thead .FilterDiv").length > 1)
    {
        $("#" + id + " [name=ListContainer] thead .FilterDiv:last").addClass("dropdown-menu-right");
    }

    core.View.ClearFilter(id);
    if (InitShowView)
    {
        core.View.GetListData(core.EntityName[id], JSON.stringify(core.View.FilterData[id]), id, pagenum, pagesize);
    }
}
core.View.BindListColgroup = function (id)
{
    var colNullTemplate = '<col {0} ></col>';
    var colsHTML = '<col width="35px"></col>';
    $.each(core.ViewField[id], function (i, v)
    {
        var width = (v.AttributeWidth == undefined || v.AttributeWidth == "") ? "" : v.AttributeWidth;
        switch (v.Type)
        {
            case "nvarchar":
            case "lookup":
            case "date":
            case "datetime":
            case "int":
            case "float":
            case "bit":
            case "picklist":
            case "ntext":
                colsHTML += $.format(colNullTemplate, width == "" ? "" : 'width="' + width + 'px"');
                break;
        }
    });
    if (core.View.Option[id].length != 0)
    {
        var optionWidth = (core.View.Option[id].length > 2 ? 2 : core.View.Option[id].length) * 100;
        colsHTML += "<col width='" + optionWidth + "px'></col>";
    }
    colsHTML += '<col />';
    return colsHTML;
}

core.View.BindListHeader = function (id)
{
    var filterTextTemplate = '<div class="form-group">\
                                <label for="{0}_fiterValue">筛选{2}</label>\
                                <input type="text" class="form-control" name="{0}_fiterValue" >\
                              </div><div class="button-panel">\
                              <button type="button" attname="{0}" atttype ="{1}" class="btn btn-primary ng-binding pull-right" onclick="core.View.filter(this,\'' + id + '\')">确定</button>\
                              <button type="button" attname="{0}" atttype ="{1}" class="btn btn-primary ng-binding pull-right rebtn" onclick="core.View.filterClear(this,\'' + id + '\')">清空</button></div>';
    var test = '<input type="input" class="form-control form-time" name="{0}_fiterValue_start" attname="{0}" atttype="{1}"  readonly/>\
                                至<input type="input" class="form-control form-time" name="{0}_fiterValue_end" attname="{0}" atttype="{1}"  readonly/>';
    //zw
    var filterDateTemplate = '<div class="form-group" atttype="datetime">\
                                <label for="{0}_fiterValue">筛选{2}</label>\
                                <input type="input" class="form-control form-time" name="{0}_fiterValue_start" atttype="datetime">\
                                至<input type="input" class="form-control form-time" name="{0}_fiterValue_end" atttype="datetime">\
                              </div><div class="button-panel">\
                              <button type="button" attname="{0}" atttype ="{1}" class="btn btn-primary ng-binding pull-right" onclick="core.View.filter(this,\'' + id + '\')">确定</button>\
                              <button type="button" attname="{0}" atttype ="{1}" class="btn btn-primary ng-binding pull-right rebtn" onclick="core.View.filterClear(this,\'' + id + '\')">清空</button></div>';

    var filterFloatlate = '<div class="form-group">\
                                <label for="{0}_fiterValue">筛选{2}</label>\
                                <input type="input" class="form-control " name="{0}_fiterValue_start" >\
                                至<input type="input" class="form-control " name="{0}_fiterValue_end" >\
                              </div><div class="button-panel">\
                              <button type="button" attname="{0}" atttype ="{1}" class="btn btn-primary ng-binding pull-right" onclick="core.View.filter(this,\'' + id + '\')">确定</button>\
                              <button type="button" attname="{0}" atttype ="{1}" class="btn btn-primary ng-binding pull-right rebtn" onclick="core.View.filterClear(this,\'' + id + '\')">清空</button></div>';

    //zw-end
    var filterPicklistTemplate = '<div class="form-group">\
                                <label for="{0}_fiterValue">筛选{3}</label><div>\
                                {2}\
                              </div></div><div class="button-panel">\
                              <button type="button" attname="{0}" atttype ="{1}" class="btn btn-primary ng-binding pull-right" onclick="core.View.filter(this,\'' + id + '\')">确定</button>\
                              <button type="button" attname="{0}" atttype ="{1}" class="btn btn-primary ng-binding pull-right rebtn" onclick="core.View.filterClear(this,\'' + id + '\')">清空</button></div>';



    var listHeaderTemplate = core.View.isHaveFilter[id] ? '<th attname="{3}"><span title="点击排序"  class="{2}" attname="{3}" {4}>{0} {1}</span><span class="dropdown"><span title="筛选" class="glyphicon glyphicon-filter" attname="{3}" data-toggle="dropdown"></span>\
    <div  class="dropdown-menu FilterDiv">{5}</div></span></th>'
    : '<th attname="{3}"><span title="点击排序"  class="{2}" attname="{3}" {4}>{0} {1}</span>\
   </th>';
    var listHeaders = "<th style='width:35px'><input  type=checkbox onclick='core.CheckAll(this)' id='checkall'/></th>";

    //先循环得到默认排序字段
    $.each(core.ViewField[id], function (i, v)
    {
        if (core.View.Orderby[id] == undefined)
        {
            if (v.ViewOrderBy != undefined)
            {
                core.View.Orderby[id] = { att: i, value: v.ViewOrderBy };
                return false;
            }
        }
    });


    $.each(core.ViewField[id], function (i, v)
    {

        switch (v.Type)
        {
            case "nvarchar":
            case "lookup":

                var filterhtml = String.format(filterTextTemplate, i, v.Type, v.DisplayName);

                if (typeof (core.View.Orderby[id]) == 'undefined' && v.IsPrimaryAtt)
                    core.View.Orderby[id] = { att: i, value: 'asc' };
                if (typeof (core.View.Orderby[id]) != 'undefined' && core.View.Orderby[id].att == i)
                    listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"></span>', 'th-sort th-sort-' + core.View.Orderby[id].value, i, 'onclick="core.View.Sort(this,\'' + id + '\')"', filterhtml);
                else
                    listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"></span>', 'th-sort', i, 'onclick="core.View.Sort(this,\'' + id + '\')"', filterhtml);
                break;
                //zw
            case "date":
                var filterhtml = String.format(filterDateTemplate, i, v.Type, v.DisplayName);

                if (typeof (core.View.Orderby[id]) == 'undefined' && v.IsPrimaryAtt)
                    core.View.Orderby[id] = { att: i, value: 'asc' };
                if (typeof (core.View.Orderby[id]) != 'undefined' && core.View.Orderby[id].att == i)
                    listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"></span>', 'th-sort th-sort-' + core.View.Orderby[id].value, i, 'onclick="core.View.Sort(this,\'' + id + '\')"', filterhtml);
                else
                    listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"></span>', 'th-sort', i, 'onclick="core.View.Sort(this,\'' + id + '\')"', filterhtml);
                break;
            case "datetime":
                var filterhtml = String.format(filterDateTemplate, i, v.Type, v.DisplayName);

                if (typeof (core.View.Orderby[id]) == 'undefined' && v.IsPrimaryAtt)
                    core.View.Orderby[id] = { att: i, value: 'asc' };
                if (typeof (core.View.Orderby[id]) != 'undefined' && core.View.Orderby[id].att == i)
                    listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"></span>', 'th-sort th-sort-' + core.View.Orderby[id].value, i, 'onclick="core.View.Sort(this,\'' + id + '\')"', filterhtml);
                else
                    listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"></span>', 'th-sort', i, 'onclick="core.View.Sort(this,\'' + id + '\')"', filterhtml);
                break;
                //zw-end
            case "int":
            case "float":
                var filterhtml = String.format(filterFloatlate, i, v.Type, v.DisplayName);

                if (typeof (core.View.Orderby[id]) == 'undefined' && v.IsPrimaryAtt)
                    core.View.Orderby[id] = { att: i, value: 'asc' };
                if (typeof (core.View.Orderby[id]) != 'undefined' && core.View.Orderby[id].att == i)
                    listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"></span>', 'th-sort th-sort-' + core.View.Orderby[id].value, i, 'onclick="core.View.Sort(this,\'' + id + '\')"', filterhtml);
                else
                    listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"></span>', 'th-sort', i, 'onclick="core.View.Sort(this,\'' + id + '\')"', filterhtml);
                break;
            case "bit":
                var radios = core.Util.CreateRadios("filter" + i, [{ Value: 0, Text: '否' }, { Value: 1, Text: '是' }]);
                var filterhtml = String.format(filterPicklistTemplate, i, v.Type, radios, v.DisplayName);

                if (typeof (core.View.Orderby[id]) == 'undefined' && v.IsPrimaryAtt)
                    core.View.Orderby[id] = { att: i, value: 'asc' };
                if (typeof (core.View.Orderby[id]) != 'undefined' && core.View.Orderby[id].att == i)
                    listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"></span>', 'th-sort th-sort-' + core.View.Orderby[id].value, i, 'onclick="core.View.Sort(this,\'' + id + '\')"', filterhtml);
                else
                    listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"></span>', 'th-sort', i, 'onclick="core.View.Sort(this,\'' + id + '\')"', filterhtml);
                break;
            case "picklist":
                var Checkbox = core.Util.CreateCheckbox("filter" + i, core.EntityOption[id][i]);
                var filterhtml = String.format(filterPicklistTemplate, i, v.Type, Checkbox, v.DisplayName);

                if (typeof (core.View.Orderby[id]) == 'undefined' && v.IsPrimaryAtt)
                    core.View.Orderby[id] = { att: i, value: 'asc' };
                if (typeof (core.View.Orderby[id]) != 'undefined' && core.View.Orderby[id].att == i)
                    listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"></span>', 'th-sort th-sort-' + core.View.Orderby[id].value, i, 'onclick="core.View.Sort(this,\'' + id + '\')"', filterhtml);
                else
                    listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"></span>', 'th-sort', i, 'onclick="core.View.Sort(this,\'' + id + '\')"', filterhtml);
                break;
            case "ntext":
                var filterhtml = String.format(filterTextTemplate, i, v.Type, v.DisplayName);
                listHeaders += String.format(listHeaderTemplate, v.DisplayName, null, null, null, null, filterhtml);
                break;
            case "key":
                //listHeaders += String.format(listHeaderTemplate, "");
                break;
        }
    });
    if (core.View.Orderby[id] == undefined)
    {
        $.each(core.ViewField[id], function (i, v)
        {
            if (core.View.Orderby[id] == undefined)
            {
                switch (v.Type)
                {
                    case "nvarchar":
                    case "lookup":
                    case "date":
                    case "datetime":
                    case "int":
                    case "float":
                    case "bit":
                    case "picklist":
                        core.View.Orderby[id] = { att: i, value: 'asc' }
                        break;
                }
            }
        });
    }

    if (core.View.Option[id].length != 0)
    {
        listHeaders += "<th>操作</th>";
    }
    listHeaders += "<th></th>";
    return String.format('<tr>{0}</tr>', listHeaders);

}
core.View.BindListItem = function (data, id)
{
    core.ListData[id] = data;
    var rowTemplate = '<tr etn="{0}" oid="{1}" ondblclick="core.View.dblclick(this)">{2}</tr>'
    var colCheckBoxTemplate = '<td><input type="checkbox"  etn="{0}" oid="{1}"/></td>';
    var colTextTemplate = '<td>{0}</td>';
    var colLookupTemplate = '<td><a href="#" etn="{2}" oid="{1}" onclick="core.OpenEntity(this,\'' + id + '\');" style="color:#333">{0}</a></td>';
    var colPickTemplate = '<td>{0}</td>';
    var colUniqueTemplate = '<td><a href="#" etn="{0}" oid="{1}" onclick="core.OpenEntity(this,\'' + id + '\');"><span class="glyphicon glyphicon-tags small"></span> {2}</a></td>';
    var colBitTemplate = '<td>{0}</td>';

    var rows = "";
    $.each(core.ListData[id].List, function (i, v)
    {
        var cols = String.format(colCheckBoxTemplate, core.EntityName[id], v[core.EntityName[id] + "id"]);
        $.each(core.ViewField[id], function (key, value)
        {
            switch (value.Type)
            {
                case "nvarchar":
                case "int":
                case "date":
                case "datetime":
                case "float":
                    if (value.IsPrimaryAtt)
                        cols += String.format(colUniqueTemplate, core.EntityName[id], v[core.EntityName[id] + "id"], v[key]);
                    else
                        cols += String.format(colTextTemplate, v[key]);
                    break;
                case "ntext":
                    cols += String.format(colTextTemplate, v[key]);
                    break;
                case "picklist":
                    cols += String.format(colPickTemplate, core.Util.GetOptionText(core.EntityOption[id][key], v[key]));
                    break;
                case "bit":
                    cols += String.format(colBitTemplate, v[key] ? "是" : (v[key] == false ? "否" : ""));
                    break;
                case "lookup":
                    if (v[key] == null)
                    {
                        cols += "<td></td>";
                    }
                    else
                    {
                        //lookup字段不能打开
                        cols += String.format(colLookupTemplate, v[key]["name"], v[key]["id"], v[key]["entityname"]);
                    }
                    break;
                case "key":
                    //listHeaders += String.format(listHeaderTemplate, "");
                    break;
            }
        });

        if (core.View.Option[id].length != 0)
        {
            cols += "<td>";
            for (var i in core.View.Option[id])
            {
                var display = "";
                if (core.View.Option[id][i]["display"] == "none")
                {
                    display = "style='display:none;' "
                }
                cols += "<button type='button' " + display + " class='btn ViewOptionBtn' onclick='" + core.View.Option[id][i]["function"] + ";'>" + core.View.Option[id][i]["name"] + "</button>  ";
            }
            cols += "</td>";
        }
        cols += "<td></td>";
        rows += String.format(rowTemplate, core.EntityName[id], v[core.EntityName[id] + "id"], cols);


    })

    return rows;
}
core.View.BindListPageing = function (id)
{
    var pageingTemplate = '{0}\\{1}(共{2}条)';
    var total = core.ListData[id].Total;
    var size = core.ListData[id].Size;
    var index = total == 0 ? 0 : core.ListData[id].Index + 1;
    var pages = Math.ceil(total / size);
    $("#" + id + " [name=pageInfo]").text(String.format(pageingTemplate, index, pages, total));
    if (total != 0)
    {
        $("#" + id + " [name=pageFirst]").parent().removeClass("disabled");
        $("#" + id + " [name=pagePrevious]").parent().removeClass("disabled");
        $("#" + id + " [name=pageLast]").parent().removeClass("disabled");
        $("#" + id + " [name=pageNext]").parent().removeClass("disabled");
        if (index == 1)
        {
            $("#" + id + " [name=pageFirst]").parent().addClass("disabled");
            $("#" + id + " [name=pagePrevious]").parent().addClass("disabled");
        }
        if (index == pages)
        {
            $("#" + id + " [name=pageLast]").parent().addClass("disabled");
            $("#" + id + " [name=pageNext]").parent().addClass("disabled");
        }
    }
    else
    {
        $("#" + id + " [name=pageFirst]").parent().addClass("disabled");
        $("#" + id + " [name=pagePrevious]").parent().addClass("disabled");
        $("#" + id + " [name=pageLast]").parent().addClass("disabled");
        $("#" + id + " [name=pageNext]").parent().addClass("disabled");
    }
}

core.View.Sort = function (src, id)
{
    var $this = $(src);
    if ($this.attr("attname") != core.View.Orderby[id].att)
    {
        var $curSort = $this.parent().parent().find(".th-sort[attname=" + core.View.Orderby[id].att + "]");
        $curSort.removeClass("th-sort-asc");
        $curSort.removeClass("th-sort-desc");
        $this.addClass("th-sort-asc");
        core.View.Orderby[id].value = "asc";
        core.View.Orderby[id].att = $this.attr("attname");
    }
    else
    {
        if ($this.hasClass("th-sort-asc"))
        {
            $this.removeClass("th-sort-asc");
            $this.addClass("th-sort-desc");
            core.View.Orderby[id].value = "desc";
        }
        else
        {
            $this.removeClass("th-sort-desc");
            $this.addClass("th-sort-asc");
            core.View.Orderby[id].value = "asc";
        }
    }

    core.View.GetListData(core.EntityName[id], JSON.stringify(core.View.FilterData[id]), id);

};

core.View.Search = function (id)
{

    var searchValue = $("#" + id + " [name=txt_searchValue]").val();
    core.View.SearchFilter[id] = {};
    core.View.SearchFilter[id]["Conditions"] = [];
    core.View.SearchFilter[id]["FilterOperator"] = "OR";
    core.View.FilterData[id]["Filters"] = [];
    if (searchValue != "")
    {
        $.each(core.ViewField[id], function (i, v)
        {
            var ConditionExpression = {};
            ConditionExpression["AttributeName"] = i;
            ConditionExpression["Operator"] = "like";
            ///cjx-modify fix lookup attribute conditionexpression
            if (v.Type == 'lookup')
            {
                var lookup = {};
                lookup["Name"] = searchValue;
                lookup["id"] = null;
                ConditionExpression["Values"] = [lookup];
            }
            else
                ConditionExpression["Values"] = [searchValue];
            core.View.SearchFilter[id]["Conditions"].push(ConditionExpression);
        });

    }
    if (core.View.SearchFilter[id]["Conditions"].length != 0)
    {
        core.View.FilterData[id]["Filters"].push(core.View.SearchFilter[id]);
    }
    core.View.GetListData(core.EntityName[id], JSON.stringify(core.View.FilterData[id]), id);
}

core.View.GetListData = function (etn, filterData, id, pagenum, pagesize)
{
    $.TL_LockScreen();
    var order = String.format("{0} {1}"
            , core.View.Orderby["ListInnerContainer"].att + (core.ViewField[id][core.View.Orderby[id].att].Type == "lookup" ? "name" : "")
            , core.View.Orderby["ListInnerContainer"].value);
    if (pagenum == undefined)
        pagenum = (core.View.PageParam[id] ? core.View.PageParam[id].pagenum : 0);
    if (pagesize == undefined)
        pagesize = (core.View.PageParam[id] ? core.View.PageParam[id].pagesize : 50);
    if (core.View.LinkEntity)
    {
        $.ajax({
            type: "post",
            url: "/Service/Data/GetN2NData.ashx",
            data: {
                "linkentityid": core.View.LinkEntity.aid,
                "Function": "Read",
                "EntityM": core.View.LinkEntity.entityM,
                "EntityA": core.View.LinkEntity.entityA,
                "EntityB": core.View.LinkEntity.entityB,
                //"EntityB": EntityName,
                "filter": filterData,
                "order": order,
                "pagenum": pagenum,
                "pagesize": pagesize,
                "ViewName": core.ViewName[id]
            },
            dataType: "json",
            success: function (data, textStatus)
            {
                $.TL_unLockScreen();
                $("#" + id + " [name=ListContainer] tbody").html(core.View.BindListItem(data, id));

                core.View.BindListPageing(id);
            },
            error: Common.AjaxError
        });
    }
    else
    {
        $.ajax({
            type: "post",
            url: ((core.View.Url[id] == "" || core.View.Url[id] == undefined) ? "/Service/Data/GetListData.ashx" : core.View.Url[id]),
            dataType: "json",
            data: { entityname: etn, order: order, pagenum: pagenum, pagesize: pagesize, filter: filterData, ViewName: core.ViewName[id] },
            success: function (data, textStatus)
            {
                $.TL_unLockScreen();
                $("#" + id + " [name=ListContainer] tbody").html(core.View.BindListItem(data, id));

                core.View.BindListPageing(id);

                if (typeof (core.View.DoAfterView) == 'function')
                {
                    core.View.DoAfterView(id);
                }

            },
            error: Common.AjaxError
        });
    }
}

core.View.NextPage = function (id)
{
    if (!$("#" + id + " [name=pageNext]").parent().hasClass("disabled"))
    {
        core.View.GetListData(core.EntityName[id], JSON.stringify(core.View.FilterData[id]), id, core.ListData[id].Index + 1);
    }
}

core.View.PrePage = function (id)
{
    if (!$("#" + id + " [name=pagePrevious]").parent().hasClass("disabled"))
    {
        core.View.GetListData(core.EntityName[id], JSON.stringify(core.View.FilterData[id]), id, core.ListData[id].Index - 1);
    }
}

core.View.LastPage = function (id)
{
    if (!$("#" + id + " [name=pageLast]").parent().hasClass("disabled"))
    {
        var total = core.ListData[id].Total;
        var size = core.ListData[id].Size;
        var pages = Math.ceil(total / size);
        core.View.GetListData(core.EntityName[id], JSON.stringify(core.View.FilterData[id]), id, pages - 1);
    }
}

core.View.FirstPage = function (id)
{
    if (!$("#" + id + " [name=pageFirst]").parent().hasClass("disabled"))
    {
        core.View.GetListData(core.EntityName[id], JSON.stringify(core.View.FilterData[id]), id, 0);
    }
}

//filter
core.View.FilterData = {};
core.View.SearchFilter = {};


core.View.filter = function (src, id)
{
    var attname = $(src).attr("attname");
    var atttype = $(src).attr("atttype");
    //zw
    var Val1 = $(src).parent().siblings().find("input").eq(0).val();
    var Val2 = $(src).parent().siblings().find("input").eq(1).val();

    var ConditionExpression = {};
    ConditionExpression["AttributeName"] = attname;

    for (var i = 0; i < core.View.FilterData[id]["Conditions"].length; i++)
    {
        if (core.View.FilterData[id]["Conditions"][i]["AttributeName"] == attname)
        {
            core.View.FilterData[id]["Conditions"].splice(i, 1)
        }
    }

    if (atttype == "datetime")
    {
        if ((Val1 == "") && (Val2 == ""))
        {
            alert("请输入日期！");
            return
        }

        var regexp = new RegExp("^([1][7-9][0-9][0-9]|[2][0][0-9][0-9])(\-)([0][1-9]|[1][0-2])(\-)([0-2][1-9]|[3][0-1])( )([0-1][0-9]|[2][0-3])(:)([0-5][0-9])$");
        if (Val1 != "" && (!regexp.test(Val1)))
        {
            alert("请输入正确的开始时间！");
            return
        }
        if (Val2 != "" && (!regexp.test(Val2)))
        {
            alert("请输入正确的截止时间！");
            return
        }
    }
    else if (atttype == "int")
    {
        if ((Val1 == "") && (Val2 == ""))
        {
            alert("请输入值！");
            return;
        }
        var reg = new RegExp("^[0-9]+$");
        if (Val1 != "" && (!reg.test(Val1)))
        {
            alert("请输入正确的起始值！");
            return;
        }
        if (Val2 != "" && (!reg.test(Val2)))
        {
            alert("请输入正确的截止值！");
            return;
        }
    }

    switch (atttype)
    {
        case "nvarchar":
        case "ntext":
            var filtervalue = $.trim($("#" + id + " [name=" + attname + "_fiterValue]").val());
            if (filtervalue != "")
            {

                ConditionExpression["Operator"] = "Like";
                ConditionExpression["Values"] = ["*" + filtervalue];

                core.View.FilterData[id]["Conditions"].push(ConditionExpression);
            }
            break;
        case "lookup":
            var filtervalue = $.trim($("#" + id + " [name=" + attname + "_fiterValue]").val());
            if (filtervalue != "")
            {

                ConditionExpression["Operator"] = "Like";

                var lookup = {};
                lookup["Name"] = "*" + filtervalue;
                lookup["id"] = null;
                ConditionExpression["Values"] = [];
                ConditionExpression["Values"].push(lookup);
                //ConditionExpression["Values"] = [{ "Name": filtervalue }];

                core.View.FilterData[id]["Conditions"].push(ConditionExpression);
            }
            break;
        case "date":
        case "datetime":
        case "int":
        case "float":
            var filtervalue_start = $.trim($("#" + id + " [name=" + attname + "_fiterValue_start]").val());
            var filtervalue_end = $.trim($("#" + id + " [name=" + attname + "_fiterValue_end]").val());
            if (filtervalue_start != "" && filtervalue_end != "")
            {

                ConditionExpression["Operator"] = "between";
                ConditionExpression["Values"] = [filtervalue_start, filtervalue_end];
                core.View.FilterData[id]["Conditions"].push(ConditionExpression);
            }
            else if (filtervalue_start != "")
            {

                ConditionExpression["Operator"] = "GreaterEqual";
                ConditionExpression["Values"] = [filtervalue_start];
                core.View.FilterData[id]["Conditions"].push(ConditionExpression);
            }
            else if (filtervalue_end != "")
            {

                ConditionExpression["Operator"] = "LessEqual";
                ConditionExpression["Values"] = [filtervalue_end];
                core.View.FilterData[id]["Conditions"].push(ConditionExpression);
            }

            break;

        case "bit":

            ConditionExpression["Operator"] = "in";
            ConditionExpression["Values"] = [];


            if ($("#" + id + " input:radio[name=filter" + attname + "]:checked").length != 0)
            {
                ConditionExpression["Values"].push($("#" + id + " input:radio[name=filter" + attname + "]:checked").val());
            }
            if (ConditionExpression["Values"].length != 0)
            {
                core.View.FilterData[id]["Conditions"].push(ConditionExpression);
            }
            break;
        case "picklist":


            ConditionExpression["Operator"] = "in";
            ConditionExpression["Values"] = [];


            $("#" + id + " [name=filter" + attname + "]:checked").each(function ()
            {
                ConditionExpression["Values"].push($(this).val());
            });
            if (ConditionExpression["Values"].length != 0)
            {
                core.View.FilterData[id]["Conditions"].push(ConditionExpression);
            }
            break;
        case "key":
            break;
    }
    core.View.GetListData(core.EntityName[id], JSON.stringify(core.View.FilterData[id]), id);
}

core.View.filterClear = function (src, id)
{
    var attname = $(src).attr("attname");
    var atttype = $(src).attr("atttype");

    switch (atttype)
    {
        case "nvarchar":

        case "ntext":
        case "lookup":
            $("#" + id + " [name=" + attname + "_fiterValue]").val("");
            break;
        case "date":
        case "datetime":
        case "int":
        case "float":
            $("#" + id + " [name=" + attname + "_fiterValue_start]").val("");
            $("#" + id + " [name=" + attname + "_fiterValue_end]").val("");
            break;
        case "bit":
        case "picklist":
            $("#" + id + " [name=filter" + attname + "]:checked").attr("checked", false);
            break;
        case "key":
            break;
    }

    for (var i = 0; i < core.View.FilterData[id]["Conditions"].length; i++)
    {
        if (core.View.FilterData[id]["Conditions"][i]["AttributeName"] == attname)
        {
            core.View.FilterData[id]["Conditions"].splice(i, 1)
        }
    }
    core.View.GetListData(core.EntityName[id], JSON.stringify(core.View.FilterData[id]), id);
}


core.View.SwitchView = function (src, id)
{
    core.ViewName[id] = $(src).val();
    //重新获取Field

    core.View.FilterData[id] = {};
    core.View.FilterData[id]["Conditions"] = [];
    core.View.FilterData[id]["Filters"] = [];

    core.View.GetEntityData(core.ViewName[id], id);


    //if (core.ViewName[id] == "RecycleView") {
    //    //负责人是自己的
    //    customFilter = {};
    //    customFilter["Conditions"] = [];
    //    customFilter["FilterOperator"] = "AND";
    //    customFilter["Filters"] = [];
    //    var cond1 = {};
    //    cond1["AttributeName"] = "OwningUser";
    //    cond1["Operator"] = "Equal";
    //    var lookup = {};
    //    lookup["Name"] = "";
    //    lookup["id"] = RD.nav.getCurrentUser().SystemUserId;

    //    cond1["Values"] = [lookup];
    //    customFilter["Conditions"].push(cond1);
    //    core.View.FilterData[id]["Filters"] = [];
    //    core.View.FilterData[id]["Filters"].push(customFilter);

    //    core.View.Option[id] = [];

    //    //如果是回收站视图，把删除按钮变成还原按钮
    //    $(".btn-sub-list span.glyphicon-trash").next().html("还原");
    //    $(".btn-sub-list span.glyphicon-trash").parent().attr('onclick', "core.Restore('" + id + "');");
    //}

    //else {

    //    core.View.Option[id] = core.View.OptionBackup[id];
    //    $(".btn-sub-list span.glyphicon-trash").next().html("删除");
    //    $(".btn-sub-list span.glyphicon-trash").parent().attr('onclick', "core.SoftDelete('" + id + "');");
    //}

    core.View.GenerateList(id, true);

}

core.View.GetEntityData = function (ViewName, id)
{
    if (typeof (ViewName) == 'undefined')
    {
        ViewName = null;
    }
    $.ajax({
        type: "post",
        url: "/Service/Data/GetEntityField.ashx",
        dataType: "json",
        async: false,
        data: {
            entityname: core.EntityName[id], viewname: ViewName
        },
        success: function (data, textStatus)
        {


            core.ViewField[id] = data["Fields"];

            core.EntityOption[id] = data["Options"];
            core.EntityViews[id] = data["Views"];

        },
        error: Common.AjaxError
    });
}


core.View.Refresh = function (id)
{
    core.View.GetListData(core.EntityName[id], JSON.stringify(core.View.FilterData[id]), id, core.ListData[id].Index);
}


core.View.ClearFilter = function (id)
{
    $("#" + id + " [name=txt_searchValue]").val("");
}


//***************************N2N 多选：添加现有记录专用***************************//
core.Lookup = {}
core.Lookup.EntityField;
core.Lookup.EntityName;
core.Lookup.Orderby = null;
core.Lookup.ListData;
core.Lookup.FromId;
core.Lookup.EntityOption;
core.Lookup.Selected = [];
//多选打开之前选中的列表
core.Lookup.SelectedBefore = [];
core.Lookup.MultiListId;
core.Lookup.MultiTextId;
core.Lookup.isCustom = false;
core.Lookup.isMulti = true;
core.View.N2N = function (src)
{
    core.Lookup.isMulti = true;
    if (core.Lookup.isMulti)
    {

        $(".lookupmodal .ForMulti").show();
        //多选oid字段
        //多选的text字段
        //显示已经选择了的
        core.Lookup.SelectedBefore = [];
        $(".lookupmodal [name=MultiSelectedList]").html("");
        //core.Lookup.MultiListId = $(this).attr("MultiList");
        //core.Lookup.MultiTextId = $(this).attr("MultiText");
        core.Lookup.SelectedBefore = [];
        //if ($("#" + core.Lookup.MultiListId).val() == "") {
        //    core.Lookup.SelectedBefore = [];
        //} else {
        //    core.Lookup.SelectedBefore = JSON.parse($("#" + core.Lookup.MultiListId).val());
        //}

        if (core.Lookup.SelectedBefore.length > 0)
        {

            for (var i in core.Lookup.SelectedBefore)
            {
                $(".lookupmodal [name=MultiSelectedList]").append($.format(SelectedTemplate, core.Lookup.SelectedBefore[i]["oid"], core.Lookup.SelectedBefore[i]["value"]));

            }
        }


    } else
    {
        $(".lookupmodal .ForMulti").hide();
    }

    //重新刷新查询条件
    core.Lookup.FilterData = {};
    core.Lookup.FilterData["Conditions"] = [];
    core.Lookup.FilterData["FilterOperator"] = "AND";
    core.Lookup.FilterData["Filters"] = [];

    core.View.BindLookupList(EntityName);

    $(".lookupmodal").modal({ backdrop: 'static', keyboard: false, show: true });
}

core.View.BindLookupList = function (etn)
{
    $(".lookupmodal").attr("etn", etn);
    $("#modal-title-etn").text(etn);
    core.Lookup.Orderby = null;
    core.Lookup.Selected = [];

    $(".lookupmodal [name=LookupListContainer] thead").html("");
    $(".lookupmodal [name=LookupListContainer] tbody").html("");
    $(".lookupmodal [name=txt_lookupsearchValue]").val("")



    core.Lookup.EntityName = etn;

    core.Lookup.BindListHeader(etn);

}
core.Lookup.BindListHeader = function (etn)
{
    core.Lookup.FilterData = { "Conditions": [], "FilterOperator": "AND", "Filters": [] };  //清空搜索条件
    $.ajax({
        type: "post",
        url: "/Service/Data/GetEntityField.ashx",
        dataType: "json",
        data: { entityname: etn, viewname: "LookupView" },
        success: function (data, textStatus)
        {
            var EntityField = data["Fields"];
            core.Lookup.EntityField = data["Fields"];
            core.Lookup.EntityOption = data["Options"];
            var listHeaderTemplate = '<th class="{2}" attname="{3}" {4}>{0} {1}</th>'
            var listHeaders = "<th><input type='checkbox' id='checkall' onclick='core.Lookup.CheckAll(this)'/></th>";
            $.each(EntityField, function (i, v)
            {
                switch (v.Type)
                {
                    case "nvarchar":
                    case "int":
                    case "float":
                    case "bit":
                    case "lookup":
                    case "date":
                    case "datetime":
                    case "picklist":

                        if (core.Lookup.Orderby == null && v.IsPrimaryAtt)
                            core.Lookup.Orderby = { att: i, value: 'asc' };
                        if (core.Lookup.Orderby != null && core.Lookup.Orderby.att == i)
                            listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"><span>', 'th-sort th-sort-' + core.Lookup.Orderby.value, i, 'onclick="core.Lookup.Sort(this)"');
                        else
                            listHeaders += String.format(listHeaderTemplate, v.DisplayName, '<span class="glyphicon"><span>', 'th-sort', i, 'onclick="core.Lookup.Sort(this)"');
                        break;
                    case "ntext":
                        listHeaders += String.format(listHeaderTemplate, v.DisplayName, null, null, null, null);
                        break;
                    case "key":
                        //listHeaders += String.format(listHeaderTemplate, "");
                        break;
                }
            });
            $("table[name='LookupListContainer'] thead").html(String.format('<tr>{0}</tr>', listHeaders));
            //$("#LookupListContainer thead").html(String.format('<tr>{0}</tr>', listHeaders));
            core.Lookup.BindListItem(etn);
        },
        error: function ()
        {
        }
    });
}
core.Lookup.BindListItem = function (etn, where, order, pagenum, pagesize)
{
    order = String.format("{0} {1} ", core.Lookup.Orderby.att, core.Lookup.Orderby.value);
    $.ajax({
        type: "post",
        url: "/Service/Data/GetListData.ashx",
        dataType: "json",
        data: { entityname: etn, filter: where, order: order, pagenum: pagenum, pagesize: pagesize, viewname: "LookupView" },
        success: function (data, textStatus)
        {

            //core.View.BindListPageing();

            var ListData = data;
            core.Lookup.ListData = ListData;
            var rowTemplate = '<tr etn="{0}" oid="{1}">{2}</tr>'
            var colCheckBoxTemplate = '<td><input type="checkbox" onchange="core.Lookup.LookupChecked(this);" etn="{0}" oid="{1}" value="{2}"/></td>';
            var colTextTemplate = '<td>{0}</td>';
            var colPickTemplate = '<td>{0}</td>';
            var colUniqueTemplate = '<td><a href="#" etn="{0}" oid="{1}" onclick="core.OpenEntity(this);"><span class="glyphicon glyphicon-tags small"></span> {2}</a></td>';

            var colBitTemplate = '<td>{0}</td>';

            var rows = "";
            $.each(ListData.List, function (i, v)
            {
                var cols = String.format(colCheckBoxTemplate, etn, v[etn + "id"], v[core.Lookup.GetPrimaryAtt()]);
                $.each(core.Lookup.EntityField, function (key, value)
                {
                    switch (value.Type)
                    {
                        case "nvarchar":
                        case "int":
                        case "date":
                        case "datetime":
                        case "float":
                            if (value.IsPrimaryAtt)
                                cols += String.format(colUniqueTemplate, etn, v[etn + "id"], v[key]);
                            else
                                cols += String.format(colTextTemplate, v[key]);
                            break;
                        case "ntext":
                            cols += String.format(colTextTemplate, v[key]);
                            break;
                        case "picklist":
                            cols += String.format(colPickTemplate, core.Lookup.GetOptionText(core.Lookup.EntityOption[key], v[key]));
                            break;
                        case "bit":
                            cols += String.format(colBitTemplate, v[key] ? '是' : '否');
                            break;
                        case "lookup":
                            if (v[key] == null)
                            {
                                cols += "<td></td>";
                            }
                            else
                            {
                                cols += String.format(colUniqueTemplate, v[key]["entityname"], v[key]["id"], v[key]["name"]);
                            }
                            break;
                        case "key":
                            //listHeaders += String.format(listHeaderTemplate, "");
                            break;
                    }
                });
                rows += String.format(rowTemplate, etn, v[etn + "id"], cols);
            })
            //$("#LookupListContainer tbody").html(rows);
            $("table[name='LookupListContainer'] tbody").html(rows);
            core.Lookup.BindListPageing();
        },
        error: function ()
        {
        }
    });
}

//zw
$(document).on('click', "table[name='LookupListContainer'] tbody tr", function (e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    var OCheckall = $(this).parent('tbody').siblings('thead').eq(0).find('tr').find('th:first').find('input');
    if (OCheckall.prop('checked'))
    {
        OCheckall.prop('checked', false);
    }
    //$('#' + id + ' [name=ListContainer] tbody tr').unbind("click");
    var checkBox = $(this).find('td:first').find('input:first');
    var OcheckBox = $(this).siblings('tr').find('td:first').find('input').prop('checked', false);
    var box = $("[name='LookupListContainer']  tbody tr input[type=checkbox][oid]");
    $(this).siblings('tr').css('background-color', '#fff');
    checkBox.prop('checked', true);
    $(this).css('background-color', '#CCE8FF');
    console.log($(this).attr('oid'));
    for (var i = 0; i < box.length; i++)
    {
        core.Lookup.LookupChecked(box.eq(i));
    }

});
$(document).on('click', "table[name='LookupListContainer'] tbody tr td input", function (e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    var tr = $(this).parent().parent();
    if ($(this).prop("checked"))
    {
        tr.css("background-color", "#CCE8FF");
    } else
    {
        tr.css("background-color", "#fff");
    }

});
//zw-end




core.Lookup.FilterData = {};
core.Lookup.FilterData["Conditions"] = [];
core.Lookup.FilterData["FilterOperator"] = "AND";
core.Lookup.FilterData["Filters"] = [];
core.Lookup.Search = function ()
{

    var searchValue = $(".lookupmodal [name=txt_lookupsearchValue]").val();
    core.Lookup.SearchFilter = {};
    core.Lookup.SearchFilter["Conditions"] = [];
    core.Lookup.SearchFilter["FilterOperator"] = "OR";
    core.Lookup.FilterData["Filters"] = [];
    if (searchValue != "")
    {

        var ConditionExpression = {};
        ConditionExpression["AttributeName"] = core.Lookup.GetPrimaryAtt();
        ConditionExpression["Operator"] = "like";

        ConditionExpression["Values"] = ["*" + searchValue];
        core.Lookup.SearchFilter["Conditions"].push(ConditionExpression);

    }
    if (core.Lookup.SearchFilter["Conditions"].length != 0)
    {
        core.Lookup.FilterData["Filters"].push(core.Lookup.SearchFilter);
    }

    core.Lookup.BindListItem(core.Lookup.EntityName, JSON.stringify(core.Lookup.FilterData));

}

core.Lookup.GetPrimaryAtt = function ()
{
    var primaryAtt = "";
    $.each(core.Lookup.EntityField, function (i, v)
    {
        if (v.IsPrimaryAtt)
        {
            primaryAtt = i;
            return false;
        }
    });
    return primaryAtt;

}


core.Lookup.BindListPageing = function ()
{
    var pageingTemplate = '{0}\\{1}';
    var total = core.Lookup.ListData.Total;
    var size = core.Lookup.ListData.Size;
    var index = total == 0 ? 0 : core.Lookup.ListData.Index + 1;
    var pages = Math.ceil(total / size);
    $(".lookupmodal [name=pageInfo]").text(String.format(pageingTemplate, index, pages));
    if (total != 0)
    {
        $(".lookupmodal [name=pageFirst]").parent().removeClass("disabled");
        $(".lookupmodal [name=pagePrevious]").parent().removeClass("disabled");
        $(".lookupmodal [name=pageLast]").parent().removeClass("disabled");
        $(".lookupmodal [name=pageNext]").parent().removeClass("disabled");
        if (index == 1)
        {
            $(".lookupmodal [name=pageFirst]").parent().addClass("disabled");
            $(".lookupmodal [name=pagePrevious]").parent().addClass("disabled");
        }
        if (index == pages)
        {
            $(".lookupmodal [name=pageLast]").parent().addClass("disabled");
            $(".lookupmodal [name=pageNext]").parent().addClass("disabled");
        }
    }
    else
    {
        $(".lookupmodal [name=pageFirst]").parent().addClass("disabled");
        $(".lookupmodal [name=pagePrevious]").parent().addClass("disabled");
        $(".lookupmodal [name=pageLast]").parent().addClass("disabled");
        $(".lookupmodal [name=pageNext]").parent().addClass("disabled");
    }
}


core.Lookup.NextPage = function ()
{
    if (!$(".lookupmodal [name=pageNext]").parent().hasClass("disabled"))
    {
        var order = String.format("{0} {1} ", core.Lookup.Orderby.att, core.Lookup.Orderby.value);
        core.Lookup.BindListItem(core.Lookup.EntityName, JSON.stringify(core.Lookup.FilterData), order, core.Lookup.ListData.Index + 1);
    }
}

core.Lookup.PrePage = function ()
{
    if (!$(".lookupmodal [name=pagePrevious]").parent().hasClass("disabled"))
    {
        var order = String.format("{0} {1} ", core.Lookup.Orderby.att, core.Lookup.Orderby.value);
        core.Lookup.BindListItem(core.Lookup.EntityName, JSON.stringify(core.Lookup.FilterData), order, core.Lookup.ListData.Index - 1);
    }
}

core.Lookup.LastPage = function ()
{
    if (!$(".lookupmodal [name=pageLast]").parent().hasClass("disabled"))
    {
        var total = core.Lookup.ListData.Total;
        var size = core.Lookup.ListData.Size;

        var pages = Math.ceil(total / size);
        var order = String.format("{0} {1} ", core.Lookup.Orderby.att, core.Lookup.Orderby.value);
        core.Lookup.BindListItem(core.Lookup.EntityName, JSON.stringify(core.Lookup.FilterData), order, pages - 1);
    }

}

core.Lookup.FirstPage = function ()
{
    if (!$(".lookupmodal [name=pageFirst]").parent().hasClass("disabled"))
    {
        var order = String.format("{0} {1} ", core.Lookup.Orderby.att, core.Lookup.Orderby.value);
        core.Lookup.BindListItem(core.Lookup.EntityName, JSON.stringify(core.Lookup.FilterData), order, 0);
    }
}

core.Lookup.GetOptionText = function (options, value)
{
    var text = "";
    $.each(options, function (i, v)
    {
        if (v.Value == value)
        {
            text = v.Text;
            return false;
        }
    });
    return text;
}


core.Lookup.MultiSelectedOK = function ()
{

    if (core.Lookup.Selected != null)
    {
        var ids = "";
        for (var i = 0; i < core.Lookup.Selected.length; i++)
        {
            ids += core.Lookup.Selected[i]["oid"] + ",";
        }
        $.ajax({
            type: "post",
            async: true,
            url: "/Service/Data/SoftOpeateN2NItem.ashx",
            dataType: "json",
            data: {
                ids: ids.substring(0, ids.length - 1),
                entityAname: $.getQueryString("entityAname"),
                //entityBname: $.getQueryString("entityname"),
                entityBname: $.getQueryString("entityBname"),
                entityMname: $.getQueryString("entityMname"),
                linkentityid: $.getQueryString("linkentityid"),
                type: "Add"
            },
            success: function (data, textStatus)
            {
                if (data.ResultCode != 0)
                {
                    $('#progress_bar').css('background-color', '#FF7E00');
                    $('#myModelContent').html("添加数据时发生错误！错误原因：" + data.ResultMessage);
                }
                else
                {
                    $(".lookupmodal").hide();
                    location.reload();
                }
            },
            error: Common.AjaxError
        });
    }
}
core.Lookup.LookupChecked = function (src)
{
    if ($(src).is(":checked"))
    {
        if (!core.Lookup.isMulti)
        {
            $(".lookupmodal [name=LookupListContainer] input[type=checkbox]").attr("checked", false);
            $(src).prop("checked", true);
            core.Lookup.Selected = [];
        }

        core.Lookup.Selected.push({ oid: $(src).attr("oid"), value: $(src).val() });

    }
    else
    {
        for (var i in core.Lookup.Selected)
        {
            if (core.Lookup.Selected[i]["oid"] == $(src).attr("oid"))
            {
                core.Lookup.Selected.splice(i, 1);
            }
        }
    }
}

core.Lookup.Sort = function (src)
{
    var $this = $(src);
    if ($this.attr("attname") != core.Lookup.Orderby.att)
    {
        var $curSort = $this.parent().find(".th-sort[attname=" + core.Lookup.Orderby.att + "]");
        $curSort.removeClass("th-sort-asc");
        $curSort.removeClass("th-sort-desc");
        $this.addClass("th-sort-asc");
        core.Lookup.Orderby.value = "asc";
        core.Lookup.Orderby.att = $this.attr("attname");
    }
    else
    {
        if ($this.hasClass("th-sort-asc"))
        {
            $this.removeClass("th-sort-asc");
            $this.addClass("th-sort-desc");
            core.Lookup.Orderby.value = "desc";
        }
        else
        {
            $this.removeClass("th-sort-desc");
            $this.addClass("th-sort-asc");
            core.Lookup.Orderby.value = "asc";
        }
    }
    var searchValue = $(".lookupmodal [name=txt_lookupsearchValue]").val();
    var where = String.format("t.{0} like N'{1}%' ", core.Lookup.GetPrimaryAtt(), searchValue);
    var order = String.format("{0} {1} ", core.Lookup.Orderby.att, core.Lookup.Orderby.value);
    if (searchValue == "")
    {
        core.Lookup.BindListItem(core.Lookup.EntityName, null, order);
    }
    else
    {
        core.Lookup.BindListItem(core.Lookup.EntityName, where, order);
    }
};

var SelectedTemplate = '&nbsp;<span style="margin-bottom:5px" class="label label-lookup" oid="{0}" >\
                                     <span >{1}</span>\
                                    <a style="cursor:pointer" onclick="core.Lookup.MultiSelectedRemove(this);" >\
                                        <span style="color:red">&times;</span></a></span>';

//多选选中
core.Lookup.MultiSelected = function ()
{
    //for (var i in core.Lookup.Selected) {
    //    //查找新添加的是否在原来列表里
    //    var canFind = false;
    //    for (var j in core.Lookup.SelectedBefore) {
    //        if (core.Lookup.SelectedBefore[j]["oid"] == core.Lookup.Selected[i]["oid"]) {
    //            canFind = true;
    //        }
    //    }
    //    if (!canFind) {
    //        //找不到，添加到选中列表中
    //        $(".lookupmodal [name=MultiSelectedList]").append($.format(SelectedTemplate, core.Lookup.Selected[i]["oid"], core.Lookup.Selected[i]["value"]));
    //        core.Lookup.SelectedBefore.push(core.Lookup.Selected[i]);
    //    }
    //}
    for (var i = 0; i < core.Lookup.Selected.length; i++)
    {
        //查找新添加的是否在原来列表里
        var canFind = false;
        for (var j in core.Lookup.SelectedBefore)
        {
            if (core.Lookup.SelectedBefore[j]["oid"] == core.Lookup.Selected[i]["oid"])
            {
                canFind = true;
                break;
            }
        }
        if (!canFind)
        {
            //找不到，添加到历史选中列表中，那么下一个循环就可以找到避免重复
            $(".lookupmodal [name=MultiSelectedList]").append($.format(SelectedTemplate, core.Lookup.Selected[i]["oid"], core.Lookup.Selected[i]["value"]));
            core.Lookup.SelectedBefore.push(core.Lookup.Selected[i]);
        }
        else
        {
            //历史中已有，则从现选项中移除
            core.Lookup.Selected.pop(core.Lookup.Selected[i])
        }
    }
}
//多选选中的移除
core.Lookup.MultiSelectedRemove = function (src)
{

    //var id = $(src).parent().attr("oid");
    //$(src).parent().remove();

    //for (var i in core.Lookup.SelectedBefore) {
    //    if (core.Lookup.SelectedBefore[i]["oid"] == id) {
    //        core.Lookup.SelectedBefore.splice(i, 1);
    //    }
    //}
    var id = $(src).parent().attr("oid");
    $(src).parent().remove();
    var i = 0; i < core.Lookup.Selected.length; i++
    for (var i = 0; i < core.Lookup.SelectedBefore; i++)
    {
        if (core.Lookup.SelectedBefore[i]["oid"] == id)
        {
            core.Lookup.SelectedBefore.splice(i, 1);
        }
    }
}

//by zgf 06.08
core.Lookup.CheckAll = function ()
{
    var checkall = $("table[name=LookupListContainer] thead").find("tr:first").find("th:first").find("input:first");
    var boxes = $("table[name=LookupListContainer] tbody tr input[type=checkbox][oid]");
    var tr = $("table[name=LookupListContainer] tbody tr");
    if (checkall.prop("checked"))
    {
        boxes.prop("checked", true);
        tr.css("background-color", "#CCE8FF");

    } else
    {
        boxes.prop("checked", false);
        tr.css("background-color", "#fff");
    }
    for (var i = 0; i < boxes.length; i++)
    {
        core.Lookup.LookupChecked(boxes.eq(i));
    }
}
//***********************************************************************//

/**********N2N移除关系***********/
core.View.RemoveExist = function ()
{
    core.View.CreateModal("提示", "<p id=\"myModelContent\">  </p>\
                        <div id=\"progress\" class=\"progress \" style=\"opacity:0;height:0px\">\
                            <div  id=\"progress_bar\" class=\"progress-bar progress-bar-striped active  \" role=\"progressbar\" aria-valuemax=\"100\" aria-valuemin=\"0\" style=\"width: 0% ;\">\
                                <span class=\"sr-only\">60%</span>\
                            </div>\
                        </div>", "移除", "取消");
    $('#ModalButton1').on('click', function ()
    {
        core.DoRemoveExist(Checked, num);
    });

    var Checked = $("[name=ListContainer] input[type=checkbox][oid]:checked");
    var num = Checked.length;

    $("#progress").css("opacity", "0");
    $("#progress").css("height", "0px");
    if (num == 0)
    {
        //$.toast("请选择要移除的数据");
        $('#myModelContent').html("请选择要移除的数据");
        //禁用删除按钮
        $('#ModalButton1').attr('disabled', "true");
        $('#ModalButton1').css('background', '#ccc');


    }
    else
    {
        //启动删除按钮
        //$.toast("确定要移除" + num + "项数据？");
        $('#myModelContent').html("确定要移除" + num + "项数据？");
        $('#ModalButton1').removeAttr('disabled');
        $('#ModalButton1').css('background', '#09c');
        //初始化进度条
        $('#progress_bar').css('width', '0%');
        $('#progress_bar').css('background-color', '#337ab7');
    }
    $("#myModal").modal({ backdrop: 'static', keyboard: false });
}
core.DoRemoveExist = function (Checked, num)
{
    //移除数据
    var ids = "";
    for (var i = 0; i < num; i++)
    {
        ids += Checked.eq(i).attr("oid") + ",";
    }
    //core.showProgressBar(index, num);
    $.ajax({
        type: "post",
        async: true,
        url: "/Service/Data/SoftOpeateN2NItem.ashx",
        dataType: "json",
        data: {
            ids: ids.substring(0, ids.length - 1),
            entityAname: $.getQueryString("entityAname"),
            //entityBname: $.getQueryString("entityname"),
            entityBname: $.getQueryString("entityBname"),
            entityMname: $.getQueryString("entityMname"),
            linkentityid: $.getQueryString("linkentityid"),
            type: "Delete"
        },
        success: function (data, textStatus)
        {
            if (data.ResultCode != 0)
            {
                $('#progress_bar').css('background-color', '#FF7E00');
                $('#myModelContent').html("移除数据时发生错误！错误原因：" + data.ResultMessage);
            }
            else
            {
                location.reload();
            }
        },
        error: Common.AjaxError
    });
}

core.View.CreateModal = function (HintMsg, bodyJs, Button1HintMsg, Button2HintMsg)
{
    $('#modaldiv').children().remove();
    var BaseModal = "       <div id=\"myModal\" class=\"modal fade \" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\">\
            <div class=\"modal-dialog\">\
                <div class=\"modal-content\">\
                    <div class=\"modal-header\" id=\"modalheader\">\
                        <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>\
                        <h4 id=\"myModalLabel\">{0}</h4>\
                    </div>\
                    <div class=\"modal-body\" id=\"modalbody\" style=\"text-align:center\">\
                    {1}\
                    </div>\
                    <div class=\"modal-footer\" id=\"modalfooter\">\
                        <button id=\"ModalButton1\" class=\"btn btn-primary \" aria-hidden=\"true\">{2}</button>\
                        <button class=\"btn btn-default\" data-dismiss=\"modal\" id=\"ModalButton2\" aria-hidden=\"true\">{3}</button>\
                    </div>\
                </div>\
            </div>\
        </div>";
    $('#modaldiv').append(String.format(BaseModal, HintMsg, bodyJs, Button1HintMsg, Button2HintMsg));
}
$(window).resize(function ()
{
    var height = window.innerHeight - 153;
    $("#ListContainer").height(height);
});